import * as userDao from '../dao/sys_user.dao';
import bcrypt from 'bcryptjs';

export async function getUserList(query: any, offset: number|string = 0, limit: number|string = 10) {
    // query 参数暂未用到，如需支持可扩展
    return await userDao.getUserList(offset, limit);
}

export async function getUserById(user_id: number) {
    return await userDao.getUserById(user_id);
}

export async function createUser(data: any) {
    let role_ids = data.role_ids;
    delete data.role_ids;
    //password 加密
    data.password = await bcrypt.hash(data.password, 10);
    const user_id = await userDao.createUser(data);
    if(user_id && role_ids){
        await userDao.updateUserRole(user_id, role_ids);
    }
    return user_id;
}

export async function updateUser(user_id: number, data: any) {
    // 保护ID为1的系统管理员用户
    if (user_id === 1) {
        throw new Error('系统管理员用户不可修改');
    }
    let role_ids = data.role_ids;
    delete data.role_ids;
    const affected = await userDao.updateUser(user_id, data);
    console.log(affected);
    if(affected > 0){
        if (role_ids){
            await userDao.updateUserRole(user_id, role_ids);
        }
    }
    return affected;
}

export async function deleteUser(user_id: number) {
    // 保护ID为1的系统管理员用户
    if (user_id === 1) {
        throw new Error('系统管理员用户不可删除');
    }
    return await userDao.deleteUser(user_id);
}

export async function getSysUserByUsername(username: string) {
    return await userDao.getUserByUsername(username);
}

export async function resetUserPassword(user_id: number, newPassword: string) {
    // 保护ID为1的系统管理员用户
    if (user_id === 1) {
        throw new Error('系统管理员用户不可重置密码');
    }
    const hashedPassword = await bcrypt.hash(newPassword, 10);
    return await userDao.updateUserPassword(user_id, hashedPassword);
}